import React, { useState } from "react";
import OptionItem from "./OptionItem";
import "./optionqs.less";
import { Button } from "@mui/material";
import { useToast } from "@/util/util";
import { SubmitAnswerApi } from "@/api";
import { useLocation } from "react-router-dom";

interface OptionQsProps {
  data: IQuestionModel;
}

// 选择题的英文转换为中文显示
const OptionQuetionMap: IQuestionTypeMap = {
  one: "单选",
  many: "多选",
  check: "判断",
};

// 选择题型的组件
export default function OptionQuetion({ data }: OptionQsProps) {
  // data.optionContent 是选择题目的选项，但是是一个json格式的字符串，所以我们需要先转换加数组
  const qs = JSON.parse(data.optionContent) as ISelectQSType[];
  // console.log(qs);

  // 准备一个数组，记录 每个选项的答案 , 如果 答案的key在这个数组里面，就是选中
  const [answers, setAnswers] = useState<string[]>([]);

  const sigleCheck = (key: string) => {
    // 这是单独处理单选的情况
    // 保持 answers里面永远只有一个元素
    setAnswers([key]);
    // 如果还有更加复杂的逻辑，可以继续往下写
  };

  // 处理多选的情况
  const multCheck = (key: string) => {
    // 把key放到answers里面
    const temp = JSON.parse(JSON.stringify(answers)) as string[];
    // 如果是已经选中，还要删除
    if (temp.includes(key)) {
      const idx = temp.indexOf(key);
      temp.splice(idx, 1);
    } else {
      // 点谁就把谁放到答案数组里面
      temp.push(key);
    }
    setAnswers(temp);
  };

  const onItemCheck = (key: string) => {
    // 如果是单选(判断+单选)
    if (data.questionType === "one" || data.questionType === "check") {
      sigleCheck(key);
    } else {
      // 多选
      multCheck(key);
    }
  };

  const toast = useToast();
  const [isAnswered, setIsAnswered] = useState(false);
  const [tip, setTip] = useState("");
  const location = useLocation();
  const state = location.state as IQuetionParams;
  const answerButton = () => {
    // 如果没有选择答案
    if (answers.length === 0) {
      toast("请先选择答案", "error");
      return;
    }
    // 选择了答案
    // 把答案同步到服务器，让服务器进行数据统计
    SubmitAnswerApi({
      categoryCode: data.categoryCode,
      actionType: "exam_test",
      actionCode: state.actionCode,
      userAnswer: answers.join(","),
      id: data.id,
    }).then((res) => {
      if (res.errCode === 0) {
        toast("提交成功", "success");
      }
    });
    // 提示用户答案
    setIsAnswered(true);
    // 如果是多选，答案是从A~D的，需要先把答案排序，再join
    setTip(answers.sort().join(",") === data.answer ? "回答正确" : "回答错误");
  };

  return (
    <div className="option-qs">
      <div className="top flex">
        {/* 渲染题目的类型 */}
        <span className="type">{OptionQuetionMap[data.questionType]}</span>
        <div className="title">{data.title}</div>
      </div>
      <div className="options">
        {qs.map((item) => (
          <OptionItem
            key={item.key}
            data={item}
            isCheck={answers.includes(item.key)}
            onClick={onItemCheck}
          />
        ))}
      </div>
      <div className="answers">
        <Button variant="outlined" onClick={answerButton}>
          确定
        </Button>

        <div
          className="show-answer"
          style={{ display: isAnswered ? "block" : "none" }}
        >
          <div className="result">{tip}</div>
          <div className="tip">参考答案</div>
          <div className="final">{data.answer}</div>
        </div>
      </div>
    </div>
  );
}
